
package com.x52im.rbchat.logic.register;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;

import com.eva.android.widget.DataLoadableActivity;
import com.eva.android.ToolKits;
import com.eva.android.widget.DataLoadingAsyncTask2;
import com.eva.android.widget.alert.AlertDialog;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.dto.DataFromServer;
import com.x52im.rbchat.Const;
import com.x52im.rbchat.R;
import com.x52im.rbchat.network.http.HttpRestHelper;
import com.x52im.rainbowchat.http.logic.dto.UserRegisterDTO;
import com.x52im.rbchat.logic.main.LoginActivity;
import com.x52im.rbchat.utils.IntentFactory;

/**
 * 用户注册界面.
 * 
 * @author Jack Jiang(http://www.52im.net/space-uid-1.html)
 * @version 1.0
 */
public class RegisterActivity extends DataLoadableActivity
{
	/** 文本编辑组件：昵称 */
	private TextView txtNickname = null;
	/** 文本编辑组件：email */
	private TextView txtEmail = null;
	/** 文本编辑组件：输入密码 */
	private TextView txtPassword = null;
	/** 文本编辑组件：确认密码 */
	private TextView txtConformPassword = null;
	
	/** 选择组件：男 */
	private RadioButton cbMan = null;
	/** 选择组件：女 */
	private RadioButton cbWomen = null;
	/** 选择组件：是否同意条款 */
	private CheckBox cbAgreeLisence = null;
	/** 选择组件：查看条款 */
	private TextView btnLookCaluse = null;

	/** 按钮：登陆 */
	private Button btnSubmit = null;

	/**
	 * 本方法由父类的onCreate()调用，子类可在此方法中实现自已的UI显示逻辑。
	 */
	@Override
	protected void initViews(Bundle savedInstanceState)
	{
		customeTitleBarResId = R.id.register_form_titleBar;
		
		//养成良好习惯：首先设置主layout，确保后绪的操作中使用到的组件都可以被find到
		setContentView(R.layout.register_form);
		
		this.setTitle(R.string.register_form_title);
		this.setLoadDataOnCreate(false);

		//各功能组件
		txtNickname = (TextView)this.findViewById(R.id.resigter_form_nicknameEdit);
		txtEmail = (TextView)this.findViewById(R.id.register_form_emailEdit);
		txtPassword = (TextView)this.findViewById(R.id.register_form_passwordEdit);
		txtConformPassword = (TextView)this.findViewById(R.id.register_form_conformPswEdit);
		
		cbMan =(RadioButton)this.findViewById(R.id.register_form_manCb); 
		cbWomen =(RadioButton)this.findViewById(R.id.register_form_womanCb); 
		cbAgreeLisence =(CheckBox)this.findViewById(R.id.register_form_agreeLisenseCb);
		btnLookCaluse = this.findViewById(R.id.register_form_to_clause);
		
		btnSubmit = (Button)this.findViewById(R.id.register_form_submitBtn);
	}
	
	/**
	 * 本方法由父类的onCreate()调用，子类可在此方法中为各UI功能组件增加事件临听。
	 */
	protected void initListeners()
	{
		btnLookCaluse.setOnClickListener(v -> startActivity(IntentFactory.createCommonWebActivity2Intent(RegisterActivity.this
				, com.x52im.rbchat.utils.ToolKits.isChinese_SimplifiedChinese()? Const.RBCHAT_REGISTER_AGREEMENT_CN_URL:Const.RBCHAT_REGISTER_AGREEMENT_EN_URL
				, $$(R.string.register_form_view_look_caluse_simple), true)));
		btnSubmit.setOnClickListener(v -> fireSave());
	}
	
	public UserRegisterDTO getFormData()
	{
		UserRegisterDTO u = new UserRegisterDTO();
		u.setNickname(String.valueOf(this.txtNickname.getText()));
		u.setUser_mail(String.valueOf(this.txtEmail.getText()).toLowerCase());
		u.setUser_psw(String.valueOf(this.txtPassword.getText()));
		u.setUser_sex(this.cbMan.isChecked() ? "1" : "0");
		return u;
	}
	
	private void fireSave()
	{
		if(String.valueOf(txtNickname.getText()).trim().length()<=0)
		{
			txtNickname.setError($$(R.string.register_form_valid_nick_name));
			return;
		}
		if(String.valueOf(txtEmail.getText()).trim().length()<=0)
		{
			txtEmail.setError($$(R.string.register_form_valid_mail));
			return;
		}
		if(!ToolKits.isEmail(String.valueOf(txtEmail.getText()).trim()))
		{
			txtEmail.setError($$(R.string.general_invild));
			return;
		}
		if(String.valueOf(txtPassword.getText()).trim().length()<=0)
		{
			txtPassword.setError($$(R.string.register_form_valid_psw));
			return;
		}
		String password = String.valueOf(this.txtPassword.getText());
		if(password !=null && !password.equals(String.valueOf(this.txtConformPassword.getText())))
		{
			txtConformPassword.setError($$(R.string.register_form_valid_psw_not_same));
			return;
		}
		if(!cbAgreeLisence.isChecked())
		{
			cbAgreeLisence.setError($$(R.string.register_form_valid_agree_role));
			return;
		}
		
		//* 开始提交注册信息
		new RegisterSubmitAsyncTask().execute();
	}
	
	/**
	 * 提交注册数据的异步多线程封装类.
	 */
	protected class RegisterSubmitAsyncTask extends DataLoadingAsyncTask2<String, Integer, DataFromServer>
	{
		private UserRegisterDTO registerData = null;
		
		public RegisterSubmitAsyncTask()
		{
			super(RegisterActivity.this, $$(R.string.general_submitting));
		}
		
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			btnSubmit.setEnabled(false);
		}
		
		/**
		 * 在后台执行实现注册信息的提交和处理结果的读取 .
		 * 
		 * @param parems 外界传进来的参数
		 * @return 查询结果，将传递给onPostExecute(..)方法
		 */
		@Override
		protected DataFromServer doInBackground(String... parems) 
		{
			//** 提交注册数据到服务端
			registerData = getFormData();
			
			// 提交请求到服务端
			return HttpRestHelper.submitRegisterToServer(registerData);
		}
		
		@Override
		protected void onPostExecute(DataFromServer result) 
		{
			super.onPostExecute(result);
			btnSubmit.setEnabled(true);
		}
		
		/**
		 * 处理服务端返回的登陆结果信息.
		 */
		protected void onPostExecuteImpl(Object jsonOfResult)
		{
			Object retVal = jsonOfResult;//dfs.getReturnValue();
			if(retVal != null)
			{
				String uid = HttpRestHelper.parseRegisterFromServer((String)retVal);
				if(!CommonUtils.isStringEmpty(uid))
				{
					// 返回值“0”表示注册邮件已经存在，本次注册失败！
					if(uid.equals("0"))
					{
						new AlertDialog.Builder(RegisterActivity.this)  
						.setTitle(R.string.general_error)
						.setMessage(R.string.register_form_error_mail_exist)
						.setPositiveButton(R.string.general_ok,   null)
						.setNegativeButton(R.string.general_cancel, null).show();
						return; // 失败了，直接return
					}
					// 注册成功
					else
					{
						registerData.setUser_uid(uid);
						Intent intent = IntentFactory.createRegisterSuccessIntent(RegisterActivity.this, registerData);
						startActivityForResult(intent, LoginActivity.REQUEST_CODE_FOR_REGISTER);
						return; // 成功了，直接return
					}
				}
			}

			//否则是出现了其它注册失败问题，弹出提示框
			new AlertDialog.Builder(RegisterActivity.this)  
				.setTitle(R.string.general_error)
				.setMessage(R.string.register_form_error_message)
				.setPositiveButton(R.string.general_ok,   null)
				.setNegativeButton(R.string.general_cancel, null).show();
			return;
		}
	}

	@Override
	protected DataFromServer queryData(String... arg0)
	{
		return null;
	}
	@Override
	protected void refreshToView(Object arg0)
	{
	}
	
	/**
	 * 处理回调通知.
	 * {@inheritDoc}
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case LoginActivity.REQUEST_CODE_FOR_REGISTER:
				// 将注册成功后的uid和密码默认填到界面上，方便用户登陆
				if (resultCode == Activity.RESULT_OK) {
					// 注册成功后，将uid和密码回传给登陆页面，方便用户立即登陆
					setResult(Activity.RESULT_OK, data);
					finish();
				}
				break;
		}
	}
}
